import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';

import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Button,
  Divider, Modal,
} from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import UpdateForm from './createFrom';
import DescView from './descView';
import SetPower from './setPower';
import styles from '../UserManage.less';
import { powerBtnFunc } from '@/utils/utils';

const FormItem = Form.Item;

/* eslint react/no-multi-comp:0 */
@connect(({ roleModels, loading }) => ({
  roleModels,
  loading: loading.models.roleModels
}))

@Form.create()
class UserManage extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    lookDescView: false,
    setPowerVisible: false,
    selectedRows: {},
    formValues: {},
    pagination: {
      pageNo: 1,
      pageSize: 15,
    },
  };

  constructor(props) {
    super(props);
  }

  columns = [
    {
      title: '角色编号',
      dataIndex: 'roleNo',
      key: 'roleNo',
    },
    {
      title: '角色名称',
      dataIndex: 'roleName',
      key: 'roleName',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'dataIndex',
      render: val => <span>{val === 1 ? '启用' : '停用'}</span>,
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          {
            powerBtnFunc('100015', [<a key={'btn'} onClick={() => this.handleUpdateModalVisible(true, record)}>修改</a>,
              <Divider key={'divider'} type="vertical"/>],
            )
          }
          {
            powerBtnFunc('100016', <a  key={'btn'} onClick={() => this.handleLookDesc(true, record)}>查看</a>,)
          }
          {
            powerBtnFunc('100066', [<Divider  key={'divider'} type="vertical"/>,
              <a key={'btn'} onClick={() => this.handlePower(true, record)}>配置</a>],
            )
          }
          {powerBtnFunc('100018',
            [<Divider key={'divider'}  type="vertical"/>,
              <a  key={'btn'} onClick={() => this.handleMenuClick(record)}>删除</a>],
          )
          }
        </Fragment>
      ),
    },
  ];


  componentDidMount() {
    const { dispatch } = this.props;

    //请求用户列表
    dispatch({
      type: 'roleModels/fetch',
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;


    this.setState({
      pagination: {
        pageNo: pagination.current,
        pageSize: 15,
      },
    });
    const params = {
      pageNo: pagination.current,
      pageSize: 15,
      ...formValues,
    };
    dispatch({
      type: 'roleModels/fetch',
      payload: params,
    });
  };
  //重置
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'roleModels/fetch',
      payload: {},
    });
  };


  handleMenuClick = e => {
    const { dispatch } = this.props;
    Modal.confirm({
      title: '确认',
      content: '确定删除该角色吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        dispatch({
          type: 'roleModels/remove',
          payload: {
            key: e.roleNo,
          },
          callback: () => {
            dispatch({
              type: 'roleModels/fetch',
            });
          },
        });
      },
    });

  };


  //搜索
  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
      };
      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'roleModels/fetch',
        payload: values,
      });
    });
  };


  //新建显示窗口
  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
      updateModalVisible: !!flag,
      selectedRows: {},
    });
  };
  //修改
  handleUpdateModalVisible = (flag, record) => {
    this.setState({
      updateModalVisible: !!flag,
      modalVisible: !flag,
      selectedRows: record,
      formVals: record,
    });
  };
  //查看
  handleLookDesc = (flag, record = {}) => {
    this.setState({
      lookDescView: !!flag,
      selectedRows: record,
    }, () => {
      if (!!flag) {
        const { dispatch } = this.props;
        dispatch({
          type: 'roleModels/getRoleDesc',
          payload: { roleNo: record.roleNo },
        });
      }
    });
  };

  handlePower = (flag, record) => {
    let _this = this;
    if (!!flag) {
      const { dispatch } = this.props;
      dispatch({
        type: 'roleModels/rolePermission',
        payload: {
          roleNo: record.roleNo,
        },
        callback() {
          _this.setState({
            setPowerVisible: !!flag,
            selectedRows: record,
          });
        },
      });
    } else {
      this.setState({
        setPowerVisible: !!flag,
        selectedRows: record,
      });
    }

  };

  //新建请求
  handleAdd = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'roleModels/add',
      payload: fields,
      callback: (response) => {
        dispatch({
          type: 'roleModels/fetch',
        });
      },
    });

    this.handleModalVisible();
  };
  //修改请求
  handleUpdate = fields => {
    const { dispatch } = this.props;
    const { pagination } = this.props;
    dispatch({
      type: 'roleModels/update',
      payload: fields,
      callback: (response) => {
        dispatch({
          type: 'roleModels/fetch',
          payload: pagination,
        });
        this.handleUpdateModalVisible(false, []);
      },
    });

  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 12, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
            <FormItem label="角色名称">
              {getFieldDecorator('roleName')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
        <span className={styles.submitButtons}>
        <Button type="primary" htmlType="submit">
        查询
        </Button>
        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
        重置
        </Button>

        </span>
          </Col>
        </Row>
      </Form>
    );
  }


  render() {
    const { roleModels: { rolePermission = [], data }, loading } = this.props;
    const { selectedRows, modalVisible, updateModalVisible, lookDescView, setPowerVisible } = this.state;
    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleUpdate: this.handleUpdate,
    };
    return (
      <PageHeaderWrapper title={'角色列表'}>
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
            <div className={styles.tableListOperator}>
              {
                powerBtnFunc('100014',
                  <Button key={'create'} icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
                    新建
                  </Button>,
                )
              }
            </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data ? data : ''}
              rowSelectHide={true}
              rowKey={'roleNo'}
              columns={this.columns}
              onChange={this.handleStandardTableChange}
            />
          </div>

        </Card>
        <DescView
          handleLookDesc={this.handleLookDesc}
          lookDescView={lookDescView}/>
        <UpdateForm
          {...parentMethods}
          updateModalVisible={updateModalVisible}
          modalVisible={modalVisible}
          values={selectedRows}
        />
        {rolePermission.length > 0 ?
          <SetPower
            setPowerVisible={setPowerVisible}
            selectedRows={setPowerVisible ? selectedRows : {}}
            rolePermission={rolePermission}
            handlePower={this.handlePower}/>
          : ''}
      </PageHeaderWrapper>
    );
  }
}

export default UserManage;
